package com.gobang.modules.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class WebSocketServer implements CommandLineRunner {
    
    @Value("${netty.websocket.port}")
    private int port;
    
    @Value("${netty.websocket.path}")
    private String path;
    
    @Value("${netty.websocket.max-frame-size}")
    private int maxFrameSize;
    
    private final WebSocketHandler webSocketHandler;
    
    @Override
    public void run(String... args) {
        new Thread(this::start).start();
    }
    
    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            
                            // HTTP编解码
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new HttpObjectAggregator(maxFrameSize));
                            
                            // WebSocket协议处理
                            pipeline.addLast(new WebSocketServerProtocolHandler(path, null, true, maxFrameSize));
                            
                            // 自定义业务处理器
                            pipeline.addLast(webSocketHandler);
                        }
                    });
            
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("WebSocket服务器启动成功，端口: {}", port);
            
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("WebSocket服务器启动失败", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
